package com.cn.wanxi.service;

import com.cn.wanxi.IO.NavModelIO;
import com.cn.wanxi.IO.NewsModelIO;
import com.cn.wanxi.model.NewsModel;
import com.cn.wanxi.util.IOReadWrite;
import com.cn.wanxi.util.Path;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class NewsService {
    public List<NewsModel> getNewsModelList() {


        /**
         * 1.写
         * 2.读
         * 3.封装
         */
        writeNote(Path.PATH.getPath(), Path.NEWS_NAME.getPath(), Path.SPLIT.getPath());
        String result = new IOReadWrite().readNote(Path.PATH.getPath(), Path.NEWS_NAME.getPath());
        return setData(result);
    }

    private List<NewsModel> setData(String result) {
        String[] results = result.split(Path.SPLIT.getPath());
        String href = results[0];
        String title = results[1];
        String content = results[2];
        href = href.replace("[", "").replace("]", "");
        title = title.replace("[", "").replace("]", "");
        content = content.replace("[", "").replace("]", "");

        List<NewsModel> list = new ArrayList<>();

        String[] titles = title.split(",");
        String[] contents = content.split(",");
        String[] hrefs = href.split(",");
        for (int i = 0; i < titles.length; i++) {
            NewsModel newsModel = new NewsModel();
            newsModel.setTitle(titles[i]);
            newsModel.setContent(contents[i]);
            newsModel.setHref(hrefs[i]);
            list.add(newsModel);
        }
        return list;
    }

    private void writeNote(String path, String fileName, String split) {
        File directory = new File(path);
        if (!directory.exists()) {
            directory.mkdirs();
        }
        File file = new File(directory, fileName);
        try {
            file.createNewFile();
            OutputStream outputStream = new FileOutputStream(file);
            NewsModelIO newsModelIO = new NewsModelIO();

            outputStream.write(Arrays.toString(newsModelIO.getHrefs()).getBytes());
            outputStream.write(split.getBytes());
            outputStream.write(Arrays.toString(newsModelIO.getTitles()).getBytes());
            outputStream.write(split.getBytes());
            outputStream.write(Arrays.toString(newsModelIO.getContents()).getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
